package com.zhaoyizhe.demo.intercepter;

import com.zhaoyizhe.demo.constant.ConstantSessionId;
import com.zhaoyizhe.demo.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstantSessionId.SESSION_ID_KEY);
        log.info("校验是否登录");
        if (userInfo == null) {
            log.warn("用户未登录");
            response.setStatus(401);
            response.getOutputStream().write("用户未登录".getBytes());
            return false;
        }
        log.info("已登录");
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }
}
